<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/18 0018
 * Time: 下午 10:41
 */

namespace app\index\controller;


use Alidayu\Alidayu;
use think\Cookie;
use think\Request;
use think\Session;
use app\admin\model\User;

class Login extends Common
{
    public function index()
    {
        if(Session::has('userid')) $this->redirect('User/index');
        if(Request::instance()->isAjax()){
            $data = Request::instance()->param();
            $user = new User();
            $login = $user::get(['u_username'=>$data['username'],'u_password'=>md5($data['password'])]);
            if($login){
                Session::set('userid',$login['id']);
                Session::set('utype',$login['u_type']);
                Session::set('phone',$login['u_username']);
                $this->success('登陆成功','User/index');
            }else{
                $this->error('账号或密码错误');
            }
        }
        return $this->fetch('index/login');
    }

    /**
     * @title   退出登录
     */
    public function logOut()
    {
        Session::set('userid',null);
        Session::set('phone',null);
        $this->success('退出登录','index');
    }

    /**
     * @title   修改密码
     */
    public function forgetPass()
    {
        if(Request::instance()->isAjax()){
            if(input('post.code')==Cookie::get('forpwdcode')){
                $user = User::get(['u_username'=>input('post.phone')]);
                if($user){
                    User::update(['id' => $user['id'], 'u_password' => md5(input('pwd'))]);
                    $this->success('已修改密码','Login/index');
                }else{
                    $this->error('不存在该账户');
                }
            }else{
                $this->error('验证码过期或错误');
            }
        }
        return $this->fetch('index/forgetPass');
    }

    /**
     * @title   发送修改密码验证码
     */
    public function phoneCode()
    {
        $phone = input('post.phone');
        if(empty(User::get(['u_username'=>$phone]))){
            $this->error('不存在该账户');
        }
        $alidayu = new Alidayu();
        $rand = rand(100000,999999);
        Cookie::set('forpwdcode',$rand,900);
        $content = '{"phone":"' . $phone . '","pwd":"' . $rand . '"}';
        $result = $alidayu->sendSms($phone, 'SMS_56610214', $content);
        //发送成功后记录到文件中
        if ($result == 0) {
            $status = '发送成功【发送修改密码验证码】';
            rwLog($phone, $status);
            $this->success('验证码发送成功');
        } else {
            $status = '发送失败【发送修改密码验证码】';
            rwLog($phone, $status);
            $this->error('验证码发送失败');
        }
    }
}